import React, { useState, useEffect } from 'react';
import { Card, DatePicker, Button, Table, message, Spin, Empty, Statistic, Row, Col, Space } from 'antd';
import { DownloadOutlined, LineChartOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { getCurrentMonthlySalary, getSalaryHistory } from '../../../api/salary';

// 移除模拟数据导入
// import { mockSalaries } from '../../../mock/mockData';

const { RangePicker } = DatePicker;

const MySalaryHistory = () => {
    const [loading, setLoading] = useState(false);
    const [dataSource, setDataSource] = useState([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });
    const [dateRange, setDateRange] = useState([dayjs().subtract(6, 'months'), dayjs()]);
    const [currentSalary, setCurrentSalary] = useState(null);
    const [currentSalaryLoading, setCurrentSalaryLoading] = useState(false);

    useEffect(() => {
        fetchCurrentSalary();
        fetchSalaryHistory();
    }, [pagination.current, pagination.pageSize]);

    // 获取当前月薪资
    const fetchCurrentSalary = async () => {
        setCurrentSalaryLoading(true);
        try {
            const response = await getCurrentMonthlySalary();
            setCurrentSalary(response.data);
        } catch (error) {
            console.error('获取当前薪资失败:', error);
            message.error('获取当前薪资失败');
        } finally {
            setCurrentSalaryLoading(false);
        }
    };

    // 获取薪资历史
    const fetchSalaryHistory = async () => {
        if (!dateRange || dateRange.length !== 2) {
            return;
        }

        setLoading(true);
        try {
            const response = await getSalaryHistory({
                startDate: dateRange[0].format('YYYY-MM-DD'),
                endDate: dateRange[1].format('YYYY-MM-DD'),
                page: pagination.current,
                pageSize: pagination.pageSize
            });

            setDataSource(response.data || []);
            setPagination({
                ...pagination,
                total: response.total || 0
            });
        } catch (error) {
            console.error('获取薪资历史失败:', error);
            message.error('获取薪资历史失败');
        } finally {
            setLoading(false);
        }
    };

    // 处理日期范围变化
    const handleDateRangeChange = (dates) => {
        setDateRange(dates);
    };

    // 处理搜索
    const handleSearch = () => {
        setPagination({
            ...pagination,
            current: 1 // 重置为第一页
        });
        fetchSalaryHistory();
    };

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination);
    };

    // 表格列定义
    const columns = [
        {
            title: '年份',
            dataIndex: 'year',
            key: 'year',
            width: 80
        },
        {
            title: '月份',
            dataIndex: 'month',
            key: 'month',
            width: 80
        },
        {
            title: '基本工资',
            dataIndex: 'base_salary',
            key: 'baseSalary',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '奖金',
            dataIndex: 'bonus',
            key: 'bonus',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '加班费',
            dataIndex: 'overtime',
            key: 'overtime',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '补贴',
            dataIndex: 'allowance',
            key: 'allowance',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '扣除',
            dataIndex: 'deduction',
            key: 'deduction',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '个人所得税',
            dataIndex: 'tax',
            key: 'tax',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '社保',
            dataIndex: 'insurance',
            key: 'insurance',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '公积金',
            dataIndex: 'fund',
            key: 'fund',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '实发工资',
            dataIndex: 'net_salary',
            key: 'netSalary',
            width: 100,
            render: (text) => `¥${parseFloat(text).toLocaleString()}`
        },
        {
            title: '发放日期',
            dataIndex: 'payment_date',
            key: 'paymentDate',
            width: 120
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            width: 150
        }
    ];

    return (
        <div className="my-salary-history-container">
            {/* 当前薪资概览 */}
            <Card 
                title="本月薪资" 
                className="current-salary-card" 
                loading={currentSalaryLoading}
                extra={
                    <Space>
                        <Button type="link" icon={<LineChartOutlined />}>查看趋势</Button>
                        <Button type="link" icon={<DownloadOutlined />}>下载明细</Button>
                    </Space>
                }
            >
                {currentSalary ? (
                    <>
                        <Row gutter={[24, 24]} className="salary-overview">
                            <Col span={6}>
                                <Statistic 
                                    title="实发工资" 
                                    value={currentSalary.net_salary} 
                                    precision={2}
                                    prefix="¥"
                                    valueStyle={{ color: '#1890ff', fontWeight: 'bold' }}
                                />
                            </Col>
                            <Col span={6}>
                                <Statistic 
                                    title="基本工资" 
                                    value={currentSalary.base_salary} 
                                    precision={2}
                                    prefix="¥"
                                />
                            </Col>
                            <Col span={6}>
                                <Statistic 
                                    title="奖金" 
                                    value={currentSalary.bonus} 
                                    precision={2}
                                    prefix="¥"
                                    valueStyle={{ color: '#52c41a' }}
                                />
                            </Col>
                            <Col span={6}>
                                <Statistic 
                                    title="加班费" 
                                    value={currentSalary.overtime} 
                                    precision={2}
                                    prefix="¥"
                                    valueStyle={{ color: '#faad14' }}
                                />
                            </Col>
                        </Row>
                        <Row gutter={[24, 24]} style={{ marginTop: '24px' }}>
                            <Col span={6}>
                                <Statistic 
                                    title="补贴" 
                                    value={currentSalary.allowance} 
                                    precision={2}
                                    prefix="¥"
                                    valueStyle={{ color: '#13c2c2' }}
                                />
                            </Col>
                            <Col span={6}>
                                <Statistic 
                                    title="个人所得税" 
                                    value={currentSalary.tax} 
                                    precision={2}
                                    prefix="-¥"
                                    valueStyle={{ color: '#cf1322' }}
                                />
                            </Col>
                            <Col span={6}>
                                <Statistic 
                                    title="社保" 
                                    value={currentSalary.insurance} 
                                    precision={2}
                                    prefix="-¥"
                                    valueStyle={{ color: '#cf1322' }}
                                />
                            </Col>
                            <Col span={6}>
                                <Statistic 
                                    title="公积金" 
                                    value={currentSalary.fund} 
                                    precision={2}
                                    prefix="-¥"
                                    valueStyle={{ color: '#cf1322' }}
                                />
                            </Col>
                        </Row>
                    </>

                ) : (
                    <Empty description="暂无本月薪资数据" />
                )}
            </Card>

            {/* 薪资历史记录 */}
            <Card
                title="薪资历史记录"
                className="salary-history-card"
                style={{ marginTop: 24 }}
                extra={
                    <Space>
                        <RangePicker
                            value={dateRange}
                            onChange={handleDateRangeChange}
                            picker="month"
                        />
                        <Button type="primary" onClick={handleSearch}>
                            查询
                        </Button>
                    </Space>
                }
            >
                <Table
                    columns={columns}
                    dataSource={dataSource}
                    loading={loading}
                    pagination={pagination}
                    onChange={handleTableChange}
                    scroll={{ x: 1500 }}
                    rowKey="id"
                />
            </Card>
        </div>
    );
};

export default MySalaryHistory;